﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using CommonFramework;

namespace ThreadFramework
{
    public class YLTime
    {
        private AutoResetEvent singalDone = new AutoResetEvent(false);
        private AutoResetEvent startOrStopSingal = new AutoResetEvent(false);

        /// <summary>时间内完成
        /// 
        /// </summary>
        public event EventHandler EvtOnTimeDone = (s, e) => { };

        public bool EnableTimeSingal = false;

        private void OnEvtOnTimeDone(object sender, EventArgs e)
        {
            EvtOnTimeDone(sender, e);
        }

        public void Init(object timeSec)
        {
            while (true)
            {
                startOrStopSingal.WaitOne();

                int Sec = (int)timeSec;
                singalDone.Reset();

                bool result = false;
                int i = 0;

                for (; i < Sec; i++)
                {
                    for (int j = 0; j < 100; j++)
                    {
                        result = singalDone.WaitOne(10);
                        if (!EnableTimeSingal)
                        {
                            OnEvtOnTimeDone(EnmTimeType.Cancel, null);
                            break;
                        }
                        if (result)
                        {
                            break;
                        }
                    }
                    if (!EnableTimeSingal) { break; }                
                    //刷新界面--刷新信号
#if DEBUG
                    Console.WriteLine(i.ToString());
#endif
                    if (result)
                    {
                        break;
                    }
                }

                if (result && i < Sec)
                {
                    OnEvtOnTimeDone(EnmTimeType.Validate, null);
                    //在等待时间段，完成指令
#if DEBUG
                    Console.WriteLine("在等待时间段，完成指令");
#endif
                }
                else//发出无效信号
                {
                    if (EnableTimeSingal)
                    {
                        OnEvtOnTimeDone(EnmTimeType.Timeout, null);
#if DEBUG
                        Console.WriteLine("发出无效信号");
#endif
                    }
                }
            }
        }

        public void SendOpenSingal()
        {
            singalDone.Set();
        }

        public void StartTimer() 
        {
            startOrStopSingal.Set();
        }
    }
}
